<?php
RegisterPlugin("yangtata_auto_pic","ActivePlugin_yangtata_auto_pic");
function ActivePlugin_yangtata_auto_pic() {
    global $zbp; 		
	if($zbp->Config('yangtata_auto_pic')->left_menu == 1){
	Add_Filter_Plugin('Filter_Plugin_Admin_LeftMenu','yangtata_auto_pic_Filter_Plugin_Admin_LeftMenu'); 
	}		
    if($zbp->Config('yangtata_auto_pic')->open == 1){//配图开启	 	
	if($zbp->Config('yangtata_auto_pic')->postedit==1){
	Add_Filter_Plugin('Filter_Plugin_Index_Begin','yangtata_auto_pic_Index_Begin');
	}else{
	Add_Filter_Plugin('Filter_Plugin_ViewPost_Template', 'yangtata_auto_pic_Filter_Plugin_ViewPost_Template');	
	}
	}
}
function yangtata_auto_pic_Index_Begin() {
	global $zbp; 
	$iar = yangtata_auto_pic_ViewAuto();
	if(isset($iar)){
		if(isset($iar['name']) && $iar['name']=='post_article_single'){
			if(isset($iar['id']) && !empty($iar['id'])){
				$id = $iar['id'];
			}
			if(isset($iar['alias']) && !empty($iar['alias'])){
				$id = $iar['alias'];
			}
			if(isset($id)){
			yangtata_auto_pic_postimg($id);
			}
		}
	}	
}
function yangtata_auto_pic_Filter_Plugin_ViewPost_Template(&$template) {
	global $zbp;    
	
		$article = $template->GetTags('article');//获取文章信息
		if($article->TypeName=='article'){	    
		$id = $article->ID;//提取文章ID;
		$sql = $zbp->db->sql->get()->select($zbp->table['Post'])->where(array('=', 'log_ID', $id))->sql;
		// 执行 SQL 语句并返回结果
		$array = $zbp->db->Query($sql);
		$content = $array[0]['log_Content'];//文章正文内容	
		$imgs = GetImagesFromHtml($content);//获取正文中全部图片
		$path = 'zb_users/upload/auto_pic/';
		$repath = $zbp->usersdir.'upload/auto_pic/';
		yangtata_auto_pic_make_dir($repath);
		$imagePath = $path.$id.'.'.$zbp->Config('yangtata_auto_pic')->img_type;
		$newpic = '/'.$imagePath;//待生成的图片
		$doing = false;
		if(!empty($imgs)){//如果正文有图片
			if($zbp->Config('yangtata_auto_pic')->isnext == 1){
				   //如果设置了跳过有图的文章,有图无操作
			}else{
				   //设置不跳过有图文章  
				if(in_array($newpic,$imgs)){
				   //如果待生成的图片已经在文章中，无操作
				}else{
				   //如果待生成的图片不在文章中
				   $doing = true;
				}
			}				
		}else{//如果正文无图片				     
		     $doing = true;
		}
		if($doing){
			yangtata_auto_pic_setimg($imagePath,$article->Title);//生成图片
			if (file_exists($imagePath)) {//检测图片是否已经生成			
			$newcontent  = yangtata_auto_pic_AddimgToContent($newpic,$content,$article->Title);				
			$article->Content = $newcontent;	
		    }
		}	
		}
	
}
function yangtata_auto_pic_ViewAuto()
{
    global $zbp;

    $original_url = $zbp->currenturl;

    $url = GetValueInArray(explode('?', $original_url), '0');

    if ($zbp->cookiespath === substr($url, 0, strlen($zbp->cookiespath))) {
        $url = substr($url, strlen($zbp->cookiespath));
    }

    foreach ($GLOBALS['hooks']['Filter_Plugin_ViewAuto_Begin'] as $fpname => &$fpsignal) {
        $fpreturn = $fpname($original_url, $url);
        if ($fpsignal == PLUGIN_EXITSIGNAL_RETURN) {
            $fpsignal = PLUGIN_EXITSIGNAL_NONE;

            return $fpreturn;
        }
    }

    $url = urldecode($url);
    $active_routes = $rewrite_routes = $default_routes = array();

    foreach ($zbp->routes as $key => $route) {
        $route['original_url'] = $original_url;
        $route['url'] = $url;
        if ($route['type'] == 'active') {
            if (GetValueInArray($route, 'suspended', false) == false) {
                $active_routes[] = $route;
            }
        } elseif ($route['type'] == 'rewrite') {
            if ($zbp->option['ZC_STATIC_MODE'] == 'REWRITE' && GetValueInArray($route, 'suspended', false) == false) {
                $rewrite_routes[] = $route;
            }
        } elseif ($route['type'] == 'default') {
            if (GetValueInArray($route, 'suspended', false) == false) {
                if (GetValueInArray($route, 'only_rewrite', false) == true) {
                    if ($zbp->option['ZC_STATIC_MODE'] == 'REWRITE') {
                        $default_routes[] = $route;
                    }
                } elseif (GetValueInArray($route, 'only_active', false) == true) {
                    if ($zbp->option['ZC_STATIC_MODE'] == 'ACTIVE') {
                        $default_routes[] = $route;
                    }
                } else {
                    $default_routes[] = $route;
                }
            }
        }
    }

    //匹配动态路由（某些情况下，在伪静开启时匹配但不输出内容，如果是符合条件就可以跳转）
    foreach ($active_routes as $key => $route) {
        $prefix = GetValueInArray($route, 'prefix', '');
        $prefix = empty($prefix) ? '' : ($prefix . '/');
        if (($url == $prefix . '') || ($url == $prefix . 'index.php') || (($zbp->option['ZC_STATIC_MODE'] == 'REWRITE') && GetValueInArray($_GET, 'rewrite', null) == true)) {
            $b = ViewAuto_Check_Get_And_Not_Get_And_Must_Get(GetValueInArray($route, 'get', array()), GetValueInArray($route, 'not_get', array()), GetValueInArray($route, 'must_get', array()));
            $b = $b && ViewAuto_Check_Request_Method(GetValueInArray($route, 'request_method', ''));
            //如果条件符合就组合参数数组并调用函数
            if ($b) {
                $array = array();
                ViewAuto_Process_Args_get($array, GetValueInArray($route, 'args_get', array()), $route);
                ViewAuto_Process_Args_with($array, GetValueInArray($route, 'args_with', array()), $route);
                ViewAuto_Process_Args_Merge($route);
                $b_redirect = ViewAuto_Check_To_Permalink($route, $array);
                $result = ViewAuto_Check_Redirect_To($route);
                return $route+$array;
            }
        }
    }

    //匹配伪静路由
    foreach ($rewrite_routes as $key => $route) {
        //如果条件符合就组合参数数组并调用函数
        $b = ViewAuto_Check_Get_And_Not_Get_And_Must_Get(GetValueInArray($route, 'get', array()), GetValueInArray($route, 'not_get', array()), GetValueInArray($route, 'must_get', array()));
        $b = $b && ViewAuto_Check_Request_Method(GetValueInArray($route, 'request_method', ''));
        if ($b) {
            $c = false;
            //$match_with_page 默认匹配1次 (false)，有page参数可以匹配2次 [false=(remove page), true=(keep page)]
            $match_with_page = $parameters = $m = array();
            ViewAuto_Get_Parameters_And_Match_with_page($route, $parameters, $match_with_page);
            foreach ($match_with_page as $match) {
                $r = ViewAuto_Get_Compiled_Urlrule($route, $match);
                if (($r != '' && preg_match($r, $url, $m) == 1) || ($r == '' && $url == '') || ($r == '' && $url == 'index.php') || ($r == '/(?J)^index\.php\/$/' && $url == '')) {
                    $array = $m;
                    ViewAuto_Process_Args_get($array, GetValueInArray($route, 'args_get', array()), $route);
                    ViewAuto_Process_Args($array, $parameters, $m);
                    ViewAuto_Process_Args_with($array, GetValueInArray($route, 'args_with', array()), $route);
                    return $route+$array;
                }
            }
           
        }
    }

    //都不能匹配时，进入一次默认路由
    foreach ($default_routes as $key => $route) {
        $b = ViewAuto_Check_Get_And_Not_Get_And_Must_Get(GetValueInArray($route, 'get', array()), GetValueInArray($route, 'not_get', array()), GetValueInArray($route, 'must_get', array()));
        $b = $b && ViewAuto_Check_Request_Method(GetValueInArray($route, 'request_method', ''));
        if ($b) {
            $array_for = array();
            $match_with_page = $parameters = $m = array();
            //判断规则是动态还是伪静规则
            $c = (isset($route['args']) && !empty($route['args']));
            $c = $c || (!isset($route['get']) && !isset($route['not_get']) && !isset($route['must_get']));
            if ($c) {
                ViewAuto_Get_Parameters_And_Match_with_page($route, $parameters, $match_with_page);
                foreach ($match_with_page as $match) {
                    $r = ViewAuto_Get_Compiled_Urlrule($route, $match);
                    if (stristr($r, 'index\.php') === false) {
                        $url = str_ireplace('index.php', '', $url);
                    }
                    if (($r != '' && preg_match($r, $url, $m) == 1) || ($r == '' && $url == '') || ($r == '' && $url == 'index.php') || ($r == '/(?J)^index\.php\/$/' && $url == '')) {
                        $array_for[] = array(true, $parameters, $m);
                    }
                }
            } else {
                $prefix = GetValueInArray($route, 'prefix', '');
                $prefix = empty($prefix) ? '' : ($prefix . '/');
                if ($prefix == '' || ($prefix == substr($url, 0, strlen($prefix)))) {
                    $array_for[] = array(true, array(), array());
                }
            }
            foreach ($array_for as $for_value) {
                if ($for_value[0] == true) {
                    $array = $for_value[2];
                    ViewAuto_Process_Args_get($array, GetValueInArray($route, 'args_get', array()), $route);
                    ViewAuto_Process_Args($array, $for_value[1], $for_value[2]);
                    ViewAuto_Process_Args_with($array, GetValueInArray($route, 'args_with', array()), $route);
                    ViewAuto_Process_Args_Merge($route);
                    return $route+$array;
                }
            }
        }
    }

    

    
}
function yangtata_auto_pic_postimg($id) {
	global $zbp;    	 
		$sql = $zbp->db->sql->get()->select($zbp->table['Post'])->where('or',array('=', 'log_ID', $id),array('=', 'log_Title', $id),array('=', 'log_Alias', $id))->sql;	    
		// 执行 SQL 语句并返回结果
		$array = $zbp->db->Query($sql);
		if(isset($array[0])){
		$content = $array[0]['log_Content'];//文章内容	
		$title = $array[0]['log_Title'];//文章标题	
		$logid = $array[0]['log_ID'];//文章id	
		$imgs = GetImagesFromHtml($content);//获取正文中全部图片
		$path = 'zb_users/upload/auto_pic/';
		$repath = $zbp->usersdir.'upload/auto_pic/';
		yangtata_auto_pic_make_dir($repath);
		$imagePath = $path.$logid.'.'.$zbp->Config('yangtata_auto_pic')->img_type;
		$newpic = '/'.$imagePath;//待生成的图片
		$doing = false;
		if(!empty($imgs)){//如果正文有图片
			if($zbp->Config('yangtata_auto_pic')->isnext == 1){
				   //如果设置了跳过有图的文章,有图无操作
			}else{
				   //设置不跳过有图文章  
				if(in_array($newpic,$imgs)){
				   //如果待生成的图片已经在文章中，无操作
				}else{
				   //如果待生成的图片不在文章中
				   $doing = true;
				}
			}				
		}else{//如果正文无图片				     
		     $doing = true;
		}
		if($doing){
			yangtata_auto_pic_setimg($imagePath,$title);//生成图片
			if (file_exists($imagePath)) {//检测图片是否已经生成			
			$newcontent  = yangtata_auto_pic_AddimgToContent($newpic,$content,$title);	
			$sdata['log_Content'] = $newcontent;
			$zbp->db->sql->get()->update($zbp->table['Post'])->where('=', 'log_ID', $logid)->data($sdata)->query;
		    }
		}	
		}
}
function yangtata_auto_pic_setimg($imagePath,$title){
	if (file_exists($imagePath)) {
		//检测如果图片已存在则无操作	
		}else {
		//如果图片不存在则生成图片
		yangtata_auto_pic_doimg($imagePath,$title);
		}
}

function yangtata_auto_pic_AddimgToContent($imagePath,$content,$title){
	global $zbp; 
	$htmltag = $zbp->Config('yangtata_auto_pic')->img_rtag;	
	$num = $zbp->Config('yangtata_auto_pic')->img_pos;
	$imageHTML = '<center><img src="'.$imagePath.'" alt="'.$title.'"></center>'; // 图片HTML代码	
	$pattern = '/<'.$htmltag.'.*?>(.*?)<\/'.$htmltag.'>/si';
	preg_match_all($pattern, $content, $matches);
	if(isset($matches[0])){		
	if ($num <= count($matches[0])) {
		$position = strpos($content, $matches[0][$num - 1]); // 找到第 $num 个<p>标签的位置         
		$newContent = substr_replace($content, $imageHTML, $position, 0); // 在找到的位置插入图片
	}else{
		$newContent = $imageHTML.$content;
	}
	}else{
		$newContent = $imageHTML.$content;
	}
	return $newContent;
}

function yangtata_auto_pic_doimg($imagePath,$title){
	    $src = yangtata_auto_pic_randgetimg();		
		if(!empty($src)){
		AddAutoloadClassDir(ZBP_PATH . 'zb_users/plugin/yangtata_auto_pic');//指定自定义类目录
		AutoloadClass('yangtata');//自动加载类
		$imgsr = new yangtata();	
        $imgsr->image_hp($src,$title,$imagePath);
		}	
		return $newimg = '/'.$imagePath;;
}
function yangtata_auto_pic_make_dir($path)
    {
        if (!file_exists($path)) {
            $mk = @mkdir($path, 0777, true);
            @chmod($path, 0777, true);
        }
        return true;
    }
function yangtata_auto_pic_randgetimg(){
	global $zbp; 
	    $con = "zb_users/plugin/yangtata_auto_pic/file/pics/";
	    $imgname = scandir($con);
		$conname = array();
	    for($y=2;$y<count($imgname);$y++){
	        $conname[] = $imgname[$y];
	    }
		if(count($conname)){
	        $num = count($conname)-1;
            $pi = rand(0,$num);
            $img = $conname[$pi];
            $src = $con.$img;	
			return $src;
		}	
		return "";
}	
function yangtata_auto_pic_jsonReturn($data,$type='JSON'){
    	header('Content-Type:application/json; charset=utf-8');
    	exit(json_encode($data));
}

function yangtata_auto_pic_checked($checked,$current=true,$echo=true){
	return yangtata_auto_pic_checked_selected( $checked, $current, $echo, 'checked' );
}
function yangtata_auto_pic_checked_selected($helper,$current,$echo,$type){
	if ( (string) $helper === (string) $current )
		$result = ' '.$type.'="'.$type.'"';
	else
		$result = '';

	if ( $echo )
		echo $result;

	return $result;
}
function yangtata_auto_pic_Filter_Plugin_Admin_LeftMenu(&$m) {
	global $zbp;
	$m["nav_yangtata_auto_pic"] = MakeLeftMenu("root", "自动配图", $zbp->host . "zb_users/plugin/yangtata_auto_pic/main.php", "nav_yangtata_auto_pic", "yangtata_auto_pic", "","icon-tools");
}
function InstallPlugin_yangtata_auto_pic() {
	global $zbp;
	if(!$zbp->HasConfig('yangtata_auto_pic')){
        $array = array(
			'open'   => 0,			
			'isnext' => 1,
			'img_size' => 14,
			'img_bg'   => 0,
			'img_bgh' => 0,
			'img_opacity'  => 66,
			'img_alpha'  => 0,
			'img_textcolor'  => '#FFFFFF',
			'img_font' => 'youshebth.ttf',
			'img_type'=>'jpg',
			'img_rtag'=>'p',
			'img_pos'=>2,
			'left_menu'=>1,
			'postedit'=>1			
		);
		foreach($array as $key=>$val){
		   $zbp->Config('yangtata_auto_pic')->$key = $val;
		}
		$zbp->SaveConfig('yangtata_auto_pic');
    }
	$path = $zbp->usersdir."upload/auto_pic/";		
    yangtata_auto_pic_make_dir($path);   
}
function UninstallPlugin_yangtata_auto_pic() {
	global $zbp;
	if($zbp->HasConfig('yangtata_auto_pic')){
		$zbp->Config('yangtata_auto_pic')->open = 0;
		$zbp->SaveConfig('yangtata_auto_pic');
	}	
}